<template>
  <el-container class="course-detail-container">
    <el-main class="course-main">
      <el-card class="course-info-card mb-4">
        <template #header>
          <div class="card-header-title">
            {{ courseStore.chooseCourse.title }}
            <!-- 点赞/点踩功能 - 仅对已选课用户显示 -->
            <div v-if="isCourseSelected && userStore.user && userStore.user.id" class="favor-buttons">
              <el-button type="primary" circle size="small" :class="{ 'is-favored': userFavorStatus === 1 }"
                @click="handleFavor(1)" :loading="favorLoading" title="点赞">
                😊
              </el-button>
              <el-button type="danger" circle size="small" :class="{ 'is-favored': userFavorStatus === 0 }"
                @click="handleFavor(0)" :loading="favorLoading" title="点踩">
                😞
              </el-button>
            </div>
          </div>
        </template>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="cover-image-wrapper">
              <img :src="courseStore.chooseCourse.coverUrl" alt="Course Cover" class="course-cover-image" />
              <el-button type="primary" :icon="Edit" circle class="edit-cover-button"
                @click="openUploadDialog"></el-button>
            </div>
          </el-col>

          <el-col :span="16">
            <p class="course-description">
              {{ courseStore.chooseCourse.description }}
            </p>
            <el-col :span="8">
              <el-rate :model-value="courseStore.chooseCourse.star" disabled show-score text-color="#ff9900"
                score-template="{value}分"></el-rate>
            </el-col>
            <el-divider></el-divider>
            <el-row>
              <el-col :span="12">
                <p>
                  <strong>分类:</strong>
                  {{ courseStore.chooseCourse.categoryName }}
                </p>
                <p>
                  <strong>难度:</strong>
                  {{ difficultyText(courseStore.chooseCourse.difficulty) }}
                </p>
              </el-col>

              <el-col :span="12">
                <p>
                  <strong>时长:</strong>
                  {{ courseStore.chooseCourse.lastingTime }} 分钟
                </p>
                <p>
                  <strong>授课老师:</strong>
                  {{ courseStore.chooseCourse.teacherName || '未知老师' }}
                </p>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-card>

      <el-card class="course-resources-card mb-4">
        <template #header>
          <div class="card-header-title">课程资源</div>
        </template>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="6" v-for="resource in courseStore.courseResources" :key="resource.id">
            <el-card shadow="hover" class="resource-item">
              <div class="resource-icon">
                <i v-if="resource.type === 'video'" class="bi bi-play-circle-fill"></i>
                <i v-else-if="resource.type === 'document'" class="bi bi-file-earmark-text-fill"></i>
              </div>
              <div class="resource-content">
                <h6 class="resource-name">{{ resource.resourceName }}</h6>
                <p class="resource-type text-muted">
                  {{ resource.type === "video" ? "视频" : "文档" }}
                </p>

                <el-button type="primary" link
                  @click="watchOnline(resource.url, resource.type, courseStore.chooseCourse.id, resource)">查看资源
                </el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-card>

      <!-- 未选课状态：显示选课按钮 -->
      <el-card v-if="!isCourseSelected" class="course-selection-card mb-4">
        <template #header>
          <div class="card-header-title">课程选择</div>
        </template>
        <div class="selection-content">
          <el-alert v-if="!userStore.user || !userStore.user.id" title="请先登录" description="登录后才能选择课程，开始学习之旅"
            type="warning" :closable="false" class="mb-4" />
          <el-alert v-else title="您还未选择这门课程" description="选择课程后即可开始学习，记录笔记和参与讨论" type="info" :closable="false"
            class="mb-4" />
          <el-button v-if="userStore.user && userStore.user.id" type="primary" size="large" @click="handleSelectCourse"
            :loading="selectingCourse">
            <i class="bi bi-plus-circle me-2"></i>
            选择这门课程
          </el-button>
          <el-button v-else type="primary" size="large" @click="goToLogin">
            <i class="bi bi-person-circle me-2"></i>
            去登录
          </el-button>
        </div>
      </el-card>

      <!-- 已选课状态：显示笔记和问答区 -->
      <template v-else>
        <el-card class="course-notes-card mb-4">
          <template #header>
            <div class="card-header-title">我的笔记</div>
          </template>

          <!-- 笔记列表 -->
          <div v-if="userStore.myNotes.length > 0" class="notes-list mb-4">
            <h6 class="mb-3">历史笔记</h6>
            <div v-for="note in userStore.myNotes" :key="note.id" class="note-item mb-3">
              <el-card shadow="hover" class="note-card">
                <div class="note-content">
                  <p class="note-text">{{ note.content }}</p>
                  <div class="note-meta">
                    <small class="text-muted">
                      <i class="bi bi-clock"></i>
                      {{ formatDate(note.createdAt || note.timestamp) }}
                    </small>
                  </div>
                </div>
              </el-card>
            </div>
          </div>

          <!-- 添加新笔记 -->
          <div class="add-note-section">
            <h6 class="mb-3">添加新笔记</h6>
            <el-input type="textarea" :rows="5" placeholder="在这里记录你的学习笔记..." v-model="newNote"></el-input>
            <el-button type="primary" class="mt-3" @click="saveNote" :loading="savingNote">
              保存笔记
            </el-button>
          </div>
        </el-card>

        <el-card class="course-qa-card">
          <template #header>
            <div class="card-header-title">问答区</div>
          </template>
          <div class="qa-section">
            <!-- 问答列表 -->
            <div v-if="courseStore.questions.length > 0" class="qa-list mb-4">
              <h6 class="mb-3">历史问答</h6>
              <div v-for="(qa, index) in courseStore.questions" :key="index" class="qa-item mb-3">
                <el-card shadow="hover" class="qa-card">
                  <div class="qa-question">
                    <h6 class="question-title">
                      <i class="bi bi-question-circle text-primary"></i>
                      问题：{{ qa.questions.content }}
                    </h6>
                    <small class="text-muted">
                      <i class="bi bi-clock"></i>
                      {{ formatDate(qa.questions.createdAt) }}
                    </small>
                  </div>

                  <div v-if="qa.answers && qa.answers.length > 0" class="qa-answers mt-3">
                    <h6 class="answer-title">
                      <i class="bi bi-chat-dots text-success"></i>
                      回答：
                    </h6>
                    <div v-for="answer in qa.answers" :key="answer.id" class="answer-item ml-4 mb-2">
                      <p class="answer-content">{{ answer.content }}</p>
                      <small class="text-muted">
                        <i class="bi bi-clock"></i>
                        {{ formatDate(answer.createdAt) }}
                      </small>
                    </div>
                  </div>
                  <div v-else class="qa-no-answer mt-3">
                    <el-tag type="info" effect="plain">
                      <i class="bi bi-hourglass-split"></i>
                      暂无回答
                    </el-tag>
                  </div>
                </el-card>
              </div>
            </div>

            <!-- 提交新问题 -->
            <div class="add-question-section">
              <h6 class="mb-3">提出新问题</h6>
              <el-input type="textarea" :rows="3" placeholder="在这里提出你的问题..." v-model="newQuestion"></el-input>
              <el-button type="primary" class="mt-3" @click="submitQuestion" :loading="submittingQuestion">
                <i class="bi bi-send"></i>
                提交问题
              </el-button>
            </div>
          </div>
        </el-card>
      </template>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useCourseStore } from "@/stores/course.js";
import { useUserStore } from "@/stores/user.js";
import UploadCoverDialog from "@/components/common/UploadCoverDialog.vue";
import { Edit, Star, StarFilled } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";

const router = useRouter();
const route = useRoute();
const courseStore = useCourseStore();
const userStore = useUserStore();

const courseResources = ref([]);
const newNote = ref("");
const newQuestion = ref("");
const selectingCourse = ref(false);
const savingNote = ref(false);
const submittingQuestion = ref(false);
const favorLoading = ref(false);
const userFavorStatus = ref(null); // null: 未操作, 1: 点赞, 0: 点踩

const difficultyText = (difficulty) => {
  switch (difficulty) {
    case 0:
      return "入门级";
    case 1:
      return "基础级";
    case 2:
      return "进阶级";
    case 3:
      return "专家级";
    default:
      return "未知";
  }
};

// 计算属性：判断当前课程是否已被用户选择
const isCourseSelected = computed(() => {
  // 如果用户未登录，直接返回false
  if (!userStore.user || !userStore.user.id) {
    return false;
  }

  // 如果数据不完整，返回false
  if (!userStore.myClass || !courseStore.chooseCourse) {
    return false;
  }

  // 检查是否已选课
  const selected = userStore.myClass.some(course =>
    course.id === courseStore.chooseCourse.id
  );

  console.log("选课状态检查:", {
    courseId: courseStore.chooseCourse.id,
    myClass: userStore.myClass,
    selected: selected
  });

  return selected;
});

// 获取用户点赞状态
const getUserFavorStatus = async (courseId) => {
  try {
    // 这里需要调用后端API获取用户的点赞状态
    // 由于后端没有提供获取点赞状态的接口，这里暂时设为null
    userFavorStatus.value = null;
  } catch (error) {
    console.error("获取点赞状态失败:", error);
    userFavorStatus.value = null;
  }
};

// 处理点赞/点踩
const handleFavor = async (favor) => {
  if (!userStore.user || !userStore.user.id) {
    ElMessage.warning("请先登录");
    return;
  }

  if (!courseStore.chooseCourse || !courseStore.chooseCourse.id) {
    ElMessage.warning("课程信息不完整");
    return;
  }

  console.log("开始点赞操作:", {
    courseId: courseStore.chooseCourse.id,
    favor: favor
  });

  try {
    favorLoading.value = true;
    await courseStore.favorCourse(
      courseStore.chooseCourse.id,
      null, // userId参数，后端会通过Token获取
      favor
    );
    userFavorStatus.value = favor;
    console.log("点赞操作成功");
  } catch (error) {
    console.error("点赞/点踩失败:", error);
    ElMessage.error("点赞操作失败，请重试");
  } finally {
    favorLoading.value = false;
  }
};

// 选课功能
const handleSelectCourse = async () => {
  if (!userStore.user || !userStore.user.id) {
    ElMessage.warning("请先登录");
    return;
  }

  try {
    selectingCourse.value = true;
    await userStore.selectCourse(courseStore.chooseCourse.id);
    // 选课成功后刷新选课列表
    await userStore.getMyCourse();
  } catch (error) {
    console.error("选课失败:", error);
  } finally {
    selectingCourse.value = false;
  }
};

// 保存笔记
const saveNote = async () => {
  if (!newNote.value.trim()) {
    ElMessage.warning("请输入笔记内容");
    return;
  }

  try {
    savingNote.value = true;
    await userStore.postNote(
      courseStore.chooseCourse.id,
      newNote.value.trim()
    );
    newNote.value = "";
    // 刷新笔记列表
    await userStore.getMyNote(courseStore.chooseCourse.id);
  } catch (error) {
    console.error("保存笔记失败:", error);
    ElMessage.error("保存笔记失败");
  } finally {
    savingNote.value = false;
  }
};

// 提交问题
const submitQuestion = async () => {
  if (!newQuestion.value.trim()) {
    ElMessage.warning("请输入问题内容");
    return;
  }

  try {
    submittingQuestion.value = true;
    await courseStore.askQuestion(
      userStore.user.id,
      courseStore.chooseCourse.id,
      newQuestion.value.trim()
    );
    newQuestion.value = "";
    // 刷新问答列表
    await courseStore.getCourseQAs(courseStore.chooseCourse.id);
  } catch (error) {
    console.error("提交问题失败:", error);
  } finally {
    submittingQuestion.value = false;
  }
};

// 跳转到登录页
const goToLogin = () => {
  router.push("/login");
};

onMounted(async () => {
  const courseId = route.params.id;

  if (courseId) {
    try {
      console.log("开始获取课程详情，课程ID:", courseId);
      await courseStore.getCourseDetail(courseId);
      console.log("课程详情获取成功:", courseStore.chooseCourse);

      await courseStore.getCourseQAs(courseId); // 获取课程问答
      console.log("课程问答获取成功:", courseStore.questions);

      // 只有在用户已登录时才获取选课信息和笔记
      if (userStore.user && userStore.user.id) {
        console.log("用户已登录，开始获取选课信息");
        await userStore.getMyCourse();
        console.log("选课信息获取成功:", userStore.myClass);

        await userStore.getMyNote(courseId);
        console.log("笔记信息获取成功:", userStore.myNotes);

        // 获取用户点赞状态
        await getUserFavorStatus(courseId);
      } else {
        console.log("用户未登录，跳过获取选课信息和笔记");
      }
    } catch (error) {
      console.error("页面初始化失败:", error);
      ElMessage.error("页面加载失败，请刷新重试");
    }
  } else {
    console.error("课程ID不存在");
    ElMessage.error("课程ID不存在");
  }
});

const uploadDialogRef = ref(null);

const openUploadDialog = () => {
  uploadDialogRef.value.open(courseStore.chooseCourse.coverUrl);
};

const handleCoverUploadSuccess = (newUrl) => {
  courseStore.chooseCourse.coverUrl = newUrl;
  // 这里可以添加调用后端接口更新课程封面的逻辑
  console.log("New cover URL:", newUrl);
};

const openResource = (url) => {
  window.open(url, "_blank");
};

const watchOnline = (url, type, courseId, resource) => {
  courseStore.chooseResource = resource;
  if (type === "video") {
    router.push({ path: "/learning", query: { url: url, courseId: courseId, resourceId: resource.id } });
  } else {
    if (url) {
      window.open(url, "_blank");
    } else {
      ElMessage.warning("资源链接无效，无法打开。");
    }
  }
};

// 格式化日期
const formatDate = (date) => {
  if (!date) return '';
  if (typeof date === 'string') date = new Date(date);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};
</script>

<style scoped>
.course-detail-container {
  padding: 20px;
  background-color: #f0f2f5;
}

.course-main {
  max-width: 1200px;
  margin: 0 auto;
}

.course-info-card .card-header-title,
.course-resources-card .card-header-title,
.course-notes-card .card-header-title,
.course-qa-card .card-header-title,
.course-selection-card .card-header-title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.favor-buttons {
  display: flex;
  gap: 8px;
}

.favor-buttons .el-button.is-favored {
  background-color: #67c23a;
  border-color: #67c23a;
  color: white;
}

.favor-buttons .el-button.is-favored.el-button--danger {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.favor-buttons .el-button {
  font-size: 16px;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cover-image-wrapper {
  position: relative;
  width: 100%;
  height: 200px;
}

.course-cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}

.edit-cover-button {
  position: absolute;
  bottom: 10px;
  right: 10px;
}

.course-description {
  font-size: 16px;
  line-height: 1.6;
  color: #555;
}

.resource-item {
  display: flex;
  align-items: center;
  padding: 15px;
  margin-bottom: 15px;
}

.resource-icon {
  font-size: 40px;
  color: #409eff;
  margin-right: 15px;
}

.resource-content {
  flex-grow: 1;
}

.resource-name {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 5px;
}

.resource-type {
  font-size: 14px;
}

.qa-section {
  padding: 10px;
}

.selection-content {
  text-align: center;
  padding: 20px;
}

.me-2 {
  margin-right: 0.5rem;
}

.notes-list {
  max-height: 400px;
  overflow-y: auto;
}

.note-item {
  margin-bottom: 15px;
}

.note-card {
  border-left: 4px solid #409eff;
}

.note-content {
  padding: 10px 0;
}

.note-text {
  margin-bottom: 10px;
  line-height: 1.6;
  color: #333;
}

.note-meta {
  border-top: 1px solid #f0f0f0;
  padding-top: 8px;
}

.add-note-section {
  border-top: 1px solid #f0f0f0;
  padding-top: 20px;
}

.qa-list {
  max-height: 500px;
  overflow-y: auto;
}

.qa-item {
  margin-bottom: 15px;
}

.qa-card {
  border-left: 4px solid #67c23a;
}

.qa-question {
  padding: 10px 0;
}

.question-title {
  color: #333;
  margin-bottom: 5px;
}

.qa-answers {
  border-top: 1px solid #f0f0f0;
  padding-top: 10px;
}

.answer-title {
  color: #67c23a;
  margin-bottom: 10px;
}

.answer-item {
  background: #f8f9fa;
  padding: 10px;
  border-radius: 6px;
  margin-bottom: 10px;
}

.answer-content {
  margin-bottom: 5px;
  color: #555;
}

.qa-no-answer {
  text-align: center;
  padding: 20px;
}

.add-question-section {
  border-top: 1px solid #f0f0f0;
  padding-top: 20px;
}

.mt-3 {
  margin-top: 1rem;
}

.mb-3 {
  margin-bottom: 1rem;
}

.mb-4 {
  margin-bottom: 1.5rem;
}

.ml-4 {
  margin-left: 1.5rem;
}

.text-primary {
  color: #409eff;
}

.text-success {
  color: #67c23a;
}

.text-muted {
  color: #909399;
}

.bi {
  margin-right: 5px;
}
</style>
